
package com.android.fitnesscenter.view.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.fitnesscenter.R;
import com.android.fitnesscenter.utils.ConfigProperties;
import com.android.fitnesscenter.utils.ConfigProperties.QueryDetailResult;
import com.android.fitnesscenter.utils.ConfigProperties.TradingType;
import com.android.fitnesscenter.utils.Loger;
import com.android.fitnesscenter.utils.MapEntity;
import com.android.fitnesscenter.utils.TimerHelper;
import com.android.fitnesscenter.utils.ViewHelper;
import com.android.fitnesscenter.view.SelectBaseActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

public class ServerQueryDetailListActivity extends SelectBaseActivity {

    private ListView listview;
    private QueryDetailListAdapter mQueryDetailListAdapter;

    @ViewInject(R.id.txt_empty)
    private TextView txt_empty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_query_detail_list_layout);
        ViewUtils.inject(this);
        txt_empty.setVisibility(View.GONE);
        initTitleBar(getString(R.string.txt_find_detail));
        initList();
        listview = (ListView) findViewById(R.id.list_view);
        mQueryDetailListAdapter = new QueryDetailListAdapter();
        listview.setAdapter(mQueryDetailListAdapter);
        listview.setOnItemClickListener(mOnItemClickListener);
    }

    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MapEntity entity = mList.get(position);
            Intent intent = new Intent(ServerQueryDetailListActivity.this, ServerModifyDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("entity", entity);
            intent.putExtras(bundle);
            startActivityForResult(intent, 0x0001);
        }
    };

    private void initList() {
        mList = new ArrayList<MapEntity>();
        mOperateStrs = new String[] {
                "全部", "充值", "缴费"
        };
        queryByAdminDetail(getToken(), mCurUser, mCurOperate, mCurDate);
    }

    private void queryByAdminDetail(String token, String username, String type, String date) {
        RequestParams params = new RequestParams();
        HttpUtils http = new HttpUtils();
        String imei = getIMEI();
        params.addBodyParameter("token", token);
        params.addBodyParameter("imei", imei);
        if (!TextUtils.isEmpty(username)) {
            params.addBodyParameter("username", username);
        }
        type = ConfigProperties.getTradingType(type);
        if (!TextUtils.isEmpty(type)) {
            params.addBodyParameter("type", type);
        }
        if (!TextUtils.isEmpty(date)) {
            params.addBodyParameter("date", date);
        }
        String url = ConfigProperties.SERVICE_URL + "queryByAdminDetail.do";
        Loger.e("token is " + token + " imei is " + imei + " username is " + username + " type is " + type
                + " date is " + date);
        Loger.e("url is " + url + " params is " + params);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (mDialog == null) {
                    mDialog = new ProgressDialog(ServerQueryDetailListActivity.this);
                }
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.setMessage("查询账户明细中,请等待...");
                mDialog.show();
                if (mList != null) {
                    mList.clear();
                }
                if (mQueryDetailListAdapter != null) {
                    mQueryDetailListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> stringResponseInfo) {
                if (ServerQueryDetailListActivity.this != null && !ServerQueryDetailListActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    if (stringResponseInfo != null && !TextUtils.isEmpty(stringResponseInfo.result)) {
                        Loger.e("stringResponseInfo is " + stringResponseInfo.result);
                        try {
                            JSONObject jsonObject = new JSONObject(stringResponseInfo.result);
                            if (jsonObject != null) {
                                boolean success = jsonObject.getBoolean("success");
                                if (success) {
                                    parseQueryDetail(jsonObject);
                                } else {
                                    String msg = jsonObject.getString("message");
                                    if (TextUtils.equals(msg, "查询用户帐户出错")) {
                                        mList.clear();
                                    } else {
                                        new ViewHelper(ServerQueryDetailListActivity.this).showBTNDialog(msg);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ViewHelper(ServerQueryDetailListActivity.this).showBTNDialog("账户明细查找失败,请重试!");
                    }
                    if (mList == null || mList.size() == 0) {
                        txt_empty.setVisibility(View.VISIBLE);
                    } else {
                        txt_empty.setVisibility(View.GONE);
                    }
                    mQueryDetailListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                if (ServerQueryDetailListActivity.this != null && !ServerQueryDetailListActivity.this.isFinishing()) {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                    Loger.e("onFailure msg is " + msg);
                    new ViewHelper(ServerQueryDetailListActivity.this).showErrorDialog(error);
                }
            }
        });

    }

    private void parseQueryDetail(JSONObject jsonObject) throws JSONException {
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            JSONObject jSObject = (JSONObject) jsonArray.get(i);
            String id = jSObject.getString(QueryDetailResult.ID_STR);
            String completeTime = jSObject.getString(QueryDetailResult.COMPLETE_TIME_STR);
            String status = jSObject.getString(QueryDetailResult.STATUS_STR);
            String type = jSObject.getString(QueryDetailResult.TYPE_STR);
            String money = jSObject.getString(QueryDetailResult.MONEY_STR);
            String username = jSObject.getString(QueryDetailResult.USER_NAME_STR);
            MapEntity entity = new MapEntity();
            entity.setValue(QueryDetailResult.ID, id);
            entity.setValue(QueryDetailResult.COMPLETE_TIME, completeTime);
            entity.setValue(QueryDetailResult.STATUS, status);
            entity.setValue(QueryDetailResult.MONEY, money);
            entity.setValue(QueryDetailResult.TYPE, type);
            entity.setValue(QueryDetailResult.USER_NAME, username);
            mList.add(entity);
        }
    }

    private class QueryDetailListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(ServerQueryDetailListActivity.this).inflate(
                        R.layout.server_query_detail_list_item_layout, null);
                viewHolder = new ViewHolder();
                viewHolder.txt_user = (TextView) convertView.findViewById(R.id.txt_user);
                viewHolder.txt_operate = (TextView) convertView.findViewById(R.id.txt_operate);
                viewHolder.txt_operate_money = (TextView) convertView.findViewById(R.id.txt_operate_money);
                viewHolder.txt_time = (TextView) convertView.findViewById(R.id.txt_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            bindView(viewHolder, position);
            return convertView;
        }

        private void bindView(ViewHolder viewHolder, int position) {
            MapEntity entity = mList.get(position);
            viewHolder.txt_user.setText(entity.getString(QueryDetailResult.USER_NAME));
            String time = entity.getString(QueryDetailResult.COMPLETE_TIME);
            viewHolder.txt_time.setText(TimerHelper.formatTime(time));
            String operate_money = entity.getString(QueryDetailResult.MONEY);
            String type = entity.getString(QueryDetailResult.TYPE);
            String tradingType = "";
            int colorId = 0;
            if (TextUtils.equals(TradingType.PAY, type)) {
                tradingType = getString(R.string.txt_pay);
                colorId = getResources().getColor(R.color.holo_red_light);
                operate_money = "-" + operate_money;
            } else if (TextUtils.equals(TradingType.TOP_UP, type)) {
                colorId = getResources().getColor(R.color.holo_green_light);
                operate_money = "+" + operate_money;
                tradingType = getString(R.string.txt_top_up);
            }
            viewHolder.txt_operate_money.setTextColor(colorId);
            viewHolder.txt_operate.setText(tradingType);
            viewHolder.txt_operate_money.setText(operate_money);

        }

        public class ViewHolder {
            public TextView txt_user;
            public TextView txt_operate;
            public TextView txt_operate_money;
            public TextView txt_time;
        }

    }

    @Override
    protected void titlebarMethod(int id) {
        switch (id) {
            case R.id.txt_user:
                queryMembersByType(FROM_QUERY_DETAIL_LIST_ACTIVITY);
                break;
            case R.id.txt_operate:
                mCurType = 1;
                showPopWindows();
                break;
            case R.id.txt_time:
                selectTime();
                break;
        }
    }

    @Override
    protected List<HashMap<String, String>> getDataByType() {
        String[] valuesStrs = null;
        switch (mCurType) {
            case 0:
                valuesStrs = mUserStrs;
                break;
            case 1:
                valuesStrs = mOperateStrs;
                break;
        }
        List<HashMap<String, String>> title_list = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < valuesStrs.length; i++) {
            HashMap<String, String> map_title = new HashMap<String, String>();
            map_title.put("title", valuesStrs[i]);
            title_list.add(map_title);
        }
        return title_list;
    }

    @Override
    protected void requestData(String token, String user, String operate, String date) {
        queryByAdminDetail(getToken(), mCurUser, mCurOperate, mCurDate);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            queryByAdminDetail(getToken(), mCurUser, mCurOperate, mCurDate);
        }
    }
}
